import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/bookquiz.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/widgets/BGExamWidget.dart';
import 'package:ichinesereader/models/book/BookQuiz.dart';
import 'package:ichinesereader/pages/common/bookSettings.dart';
import 'package:ichinesereader/utils/log.dart';

class BookQuizReviewer extends StatefulWidget {
  BookQuizReviewer({Key? key, required this.bookId, this.bookTitle})
      : super(key: key);
  final String bookId;
  final String? bookTitle;
  static const String routeName = '/book/quiz';

  @override
  State<BookQuizReviewer> createState() => _BookQuizReviewerState();
}

class _BookQuizReviewerState extends State<BookQuizReviewer> {
  final BookQuizController _bookQuizController = Get.put(BookQuizController());
  final box = Hive.box('appconfig');

  List<QuestionItem> questionItems = [];
  BookQuiz bookQuiz = BookQuiz();
  String _lang = 'Mandarin';
  String _language = 'Simplified';
  TextOptions _textOption = TextOptions.Simplified;
  AudioOptions _audioOption = AudioOptions.Mandarin;
  bool _showAnswer = false;

  @override
  void initState() {
    _lang = box.get('UserLang') ?? 'Mandarin';
    _language = box.get('UserLanguage') ?? 'Simplified';

    if (_language == 'Traditional') {
      _textOption = TextOptions.Traditional;
    }

    if (_lang == 'Cantonese') {
      _audioOption = AudioOptions.Cantonese;
    }

    _bookQuizController
        .getBookQuiz(widget.bookId, _textOption, _audioOption)
        .then((quiz) {
      setState(() {
        questionItems = _bookQuizController.fromBookQuizToQuestionItems(
            quiz, _textOption, _audioOption);

        if (_showAnswer == false) {
          questionItems.forEach((item) {
            if (item.body != null && item.body![0].isNotEmpty)
              item.body?[0].forEach((qbody) {
                qbody.baseValue = '@@${qbody.baseValue}';
              });
          });
        } else {
          questionItems.forEach((item) {
            if (item.body != null && item.body![0].isNotEmpty)
              item.body?[0].forEach((qbody) {
                qbody.baseValue = qbody.baseValue?.replaceAll('@@', '');
              });
          });
        }
      });
    });
    super.initState();
  }

  buildFloatingActionButtons() {
    return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      FloatingActionButton(
        heroTag: 'showquizanswer',
        tooltip: !_showAnswer ? 'Show Answers' : 'Hide Answers',
        onPressed: () {
          setState(() {
            _showAnswer = !_showAnswer;
            if (_showAnswer == false) {
              questionItems.forEach((item) {
                if (item.body != null && item.body![0].isNotEmpty)
                  item.body?[0].forEach((qbody) {
                    qbody.baseValue = '@@${qbody.baseValue}';
                  });
              });
            } else {
              questionItems.forEach((item) {
                if (item.body != null && item.body![0].isNotEmpty)
                  item.body?[0].forEach((qbody) {
                    qbody.baseValue = qbody.baseValue?.replaceAll('@@', '');
                  });
              });
            }
          });
        },
        elevation: 5,
        splashColor: Colors.grey,
        child: _showAnswer == true
            ? Icon(Icons.key)
            : Icon(Icons.key_off_outlined),
      ),
    ]);
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build common book quiz viewer for teacher');
    return Scaffold(
      appBar: AppBar(
        title: Container(
          width: double.infinity,
          height: 40,
          child: Center(
            child: Text(this.widget.bookTitle != null
                ? this.widget.bookTitle.toString()
                : ''),
          ),
        ),
      ),
      floatingActionButton: buildFloatingActionButtons(),
      floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        primary: false,
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: questionItems
                  .map((item) => BGExamWidget(
                        questionItem: item,
                        mode: BGExamWidgetMode.Review,
                      ))
                  .toList(),
            ),
          ),
        ),
      ),
    );
  }
}
